package com.zrf.testchatgpt.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrf.testchatgpt.service.IConfigService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {
    @Autowired
    IConfigService iSysConfigService;

    public String MinioUploadBase64(JSONObject path){
        //            System.out.println("图片路径为:"+path.toString());
            //你的endpoint,本机可以不变
            String endpoint = iSysConfigService.selectConfigByKey("minio_url");
//            //你的accessKey
            String accessKey = iSysConfigService.selectConfigByKey("minio_accessKey");
            //你的sercetKey
            String secretKey = iSysConfigService.selectConfigByKey("minio_secretKey");
//            //你的bucket
            String bucketName = iSysConfigService.selectConfigByKey("minio_bucket");

            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
          String nameSuffix = UUID.randomUUID().toString() + ".png";
          nameSuffix=nameSuffix.replaceAll("-","");
        try {
//            log.info("endpoint:"+endpoint);
//            log.info("accessKey:"+accessKey);
//            log.info("secretKey:"+secretKey);
            MinioClient minioClient =MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            // 检查存储桶是否已经存在
            boolean isExist = false;
            isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            JSONArray base64=JSONArray.parseArray(path.getString("images"));
            InputStream byteArrayInputStream = base64ConvertPNG(base64.toString());


            minioClient.putObject( PutObjectArgs.builder().bucket(bucketName).object(nameSuffix).stream(
                    byteArrayInputStream, byteArrayInputStream.available(), -1)
                    .build());
        }catch (Exception e){
            e.printStackTrace();
                //log.info("minio上传出错了");
        }
        return endpoint+"/"+bucketName+"/"+nameSuffix;

    }
    public static InputStream base64ConvertPNG(String base64){
        BASE64Decoder decoder = new BASE64Decoder();
        //解码
        base64 = base64.replaceAll("\\[","");
        base64 = base64.replaceAll("]","");
        base64=base64.substring(1);
        try {

            byte[] buffer = decoder.decodeBuffer(base64);
            for(int i = 0;i<buffer.length;i++){
                if(buffer[i] < 0){
                    buffer[i] += 256;
                }
            }
            //生成流
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            return stream;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
